package mi.payment.ui.other;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.bean.temp.Transaction;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Params;
import mi.payment.controller.CheckerController;
import mi.payment.db.dao.UserInfo;
import mi.payment.settings.SignOperation;
import mi.payment.admin.SystemUserHomePageActivity;
import mi.payment.transaction.authorize.base.PreAuthorizeMainActivity;
import mi.payment.ui.base.ParentActivity;
import mi.payment.transaction.sale.HomeInputMoneyActivity;
import mi.payment.ui.director.AdministratorUserHomePageActivity;
import mi.payment.utils.MToast;
import mi.payment.utils.SettingHomePageUtils;
import mi.payment.utils.SystemDateTime;
import mi.payment.utils.transaction.CustomParamsInitTask;
import mi.payment.utils.transaction.ParamsInitTask;
import sunmi.sunmiui.dialog.DialogCreater;
import sunmi.sunmiui.dialog.LoadingDialog;
import sunmi.sunmiui.title.Title;

/**
 * 登陆界面
 *
 * @author sunmi on 2017/1/8.
 */
public class LoginActivity extends ParentActivity {

    private RelativeLayout layout_bg;
    private static final String EXTRA_SIGN_OUT = "LoginActivity_EXTRA_SIGN_OUT";

    private EditText editPwd;
    private EditText editOperationCode;
    private TextView tvLogin;
    private ImageView ivShowPwd;
    private ImageView ivLoading;
    private RelativeLayout relLogin;

    private int pwdLength;
    private int operationCodeLength;
    private boolean isShowPwd = true;

    private UserInfo userInfo;
    private LoadingDialog loadingDialog;

    private boolean canLogin = true;
    private boolean isSignOut = false;

    private boolean isRetry = false;
    private Timer timer = null;
    private TimerTask timerTask = null;
    private int timeout = 60;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (timeout >= 1) {
                timeout = timeout - 1;
                tvLogin.setText(getString(R.string.sign_in) + "( " + timeout + " )");
            } else {
                tvLogin.setText(getString(R.string.sign_in));
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initUserInfo();
    }


    @Override
    protected void onPause() {
        super.onPause();
        dismissDialog();
    }

    private void dismissDialog() {
        runOnUI(new Runnable() {

            @Override
            public void run() {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                    loadingDialog = null;
                }
            }

        });
    }

    private void initUserInfo() {
        loadingDialog = DialogCreater.createLoadingDialog(this, getString(R.string.detection_of_user_information));
        loadingDialog.show();
        executeTask(new Runnable() {

            @Override
            public void run() {
                mUserInfoModel.initTable();
                dismissDialog();
            }

        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_bg:
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.rel_show_psd:
                showPwd();
                break;
            case R.id.rel_login:
                if (canLogin) {
                    canLogin = false;
                    isRetry = true;
                    login();
                }
                break;
        }
    }

    private void login() {
        final String pwd = editPwd.getText().toString();
        final String uId = editOperationCode.getText().toString();
        startAnimation();
        relLogin.setOnClickListener(null);
        tvLogin.setText(getString(R.string.login_ing));
        checkLoginBtn();

        userInfo = mUserInfoModel.login(uId, pwd);
        if (userInfo != null) {
            if (userInfo.getUType() == 1) {
                checkIn();
            } else {
                canLogin = true;
                jumpActivity();
                checkLoginBtn();
            }
        } else {
            hideAnimation();
            canLogin = true;
            tvLogin.setText(getString(R.string.login));
            relLogin.setOnClickListener(LoginActivity.this);
            showToast(getString(R.string.account_or_password_error));
            checkLoginBtn();
        }
    }

    /**
     * 签到
     */
    private void checkIn() {
        startTimeout();

        ParamsInitTask task = new CustomParamsInitTask() {

            @Override
            protected void onPreExecuteImpl() {
                relLogin.setOnClickListener(null);
                tvLogin.setText(getString(R.string.sign_in));
            }


            @Override
            protected void onPostExecuteImpl(String code) {
                canLogin = true;
                hideAnimation();
                checkLoginBtn();
                relLogin.setOnClickListener(LoginActivity.this);
                if (TextUtils.equals(code, "00")) {
                    isRetry = false;
                    // 保存签到时间
                    int time = SystemDateTime.getCurrentYYYYMMDD();
                    SignOperation.getInstance().saveLastSignTime(time);
                    ParamsInitTask.isChecked = true;
                    showToast(getString(R.string.sign_success));
                    syncTime();
                    jumpActivity();
                } else {
                    tvLogin.setText(getString(R.string.login));
                    if (!TextUtils.equals(code, "N1") && !TextUtils.equals(code, "N2") && !TextUtils.equals(code, "N3") && !TextUtils.equals(code, "N4"))
                        showToast(getString(R.string.sign_fails, BaseErrorCode.getCode(code)));
                }
                stopTimeout();
            }

            @Override
            protected void onTaskTimeoutImpl() {
                canLogin = true;
                showToast(getString(R.string.sign_fails, BaseErrorCode.getCode("68")));
                hideAnimation();
                checkLoginBtn();
                stopTimeout();
                tvLogin.setText(getString(R.string.login));
            }

        };
        task.execute(Params.newTradeData());
    }

    /**
     * 启动签到倒计时
     */
    private void startTimeout() {
        boolean isSigninTimeout = new CheckerController(this).isSigninTimeout();
        if (isSigninTimeout) {
            timeout = 60;
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(0);
                }
            };

            timer.schedule(timerTask, 0, 1000);
        }
    }

    /**
     * 关闭签到倒计时
     */
    private void stopTimeout() {
        boolean isSigninTimeout = new CheckerController(this).isSigninTimeout();
        if (isSigninTimeout) {
            mHandler.removeCallbacksAndMessages(null);
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }

            retryLogin();
        }
    }

    /**
     * 切换IP重新登陆
     */
    private void retryLogin() {
        if (canLogin && isRetry) {
            canLogin = false;
            isRetry = false;
            login();
        }
    }

    /**
     * 同步时间
     */
    private void syncTime() {
        // 同步系统时间 现在只能拿到月日时分秒那不到年
        Calendar c = Calendar.getInstance(); // 首先要获取日历对象
        int year = c.get(Calendar.YEAR);     // 获取当前年份
        String date = Transaction.date;      // 0124
        String time = Transaction.time;      // 110223
        if (Transaction.date == null || Transaction.time == null) {
            return;
        }
        int month = Integer.parseInt(date.substring(0, 2));
        int day = Integer.parseInt(date.substring(2, 4));
        int hour = Integer.parseInt(time.substring(0, 2));
        int minute = Integer.parseInt(time.substring(2, 4));
        int second = Integer.parseInt(time.substring(4, 6));
        try {
            SystemDateTime.setSysDate(year, month - 1, day, LoginActivity.this);
            SystemDateTime.setSysTime(hour, minute, second, LoginActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
            showToast(getString(R.string.synchronization_time_error, e.toString()));
        }
    }

    private void jumpActivity() {
        if (userInfo.getUType() == 1) {
            Params.userInfo = userInfo;
        }
        switch (userInfo.getUType()) {
            case 1: // 一般操作员
                sendCloseHomeActivityBroadcast();
                SettingHomePageUtils settingHomePageUtils = new SettingHomePageUtils();
                if (settingHomePageUtils.getSettingHome() == null) {
                    openActivity(HomeInputMoneyActivity.class);
                } else {
                    if (settingHomePageUtils.getSettingHome().nowHome.equals("PreAuthorizeMainActivity")) {
                        openActivity(PreAuthorizeMainActivity.class);
                    } else {
                        openActivity(HomeInputMoneyActivity.class);
                    }
                }
                finish();
                break;
            case 2: // 管理操作员
                openActivity(AdministratorUserHomePageActivity.class);
                finish();
                break;
            case 3: // 系统管理员
                openActivity(SystemUserHomePageActivity.class);
                finish();
                break;
        }
        editOperationCode.setText("");
        editPwd.setText("");
        tvLogin.setText(getString(R.string.login));
    }

    private void showPwd() {
        if (isShowPwd) {
            editPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivShowPwd.setBackgroundResource(R.drawable.eye);
        } else {
            editPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivShowPwd.setBackgroundResource(R.drawable.eye2);
        }
        isShowPwd = !isShowPwd;
        Spannable spanText = editPwd.getText();
        Selection.setSelection(spanText, spanText.length());
    }

    private void initView() {
        //isShowBack = getIntent().getStringExtra(SHOW_BACK_EXTRA);
        layout_bg = (RelativeLayout) findViewById(R.id.layout_bg);
        isSignOut = getIntent().getBooleanExtra(EXTRA_SIGN_OUT, false);

        Title title = (Title) this.findViewById(R.id.title);
        title.setBackgroundResource(R.color.transparent);
        title.setTitleText("");
        title.setButtonVisibility(false, true, true, true);
        title.setImageViewBackDrawable(R.drawable.ic_back);
        title.setMenuClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }

        }, null, null, null);
        editOperationCode = (EditText) this.findViewById(R.id.edit_op_code);
        editPwd = (EditText) this.findViewById(R.id.edit_psd);
        ivShowPwd = (ImageView) this.findViewById(R.id.img_eye);
        View showPwdView = this.findViewById(R.id.rel_show_psd);
        relLogin = (RelativeLayout) this.findViewById(R.id.rel_login);
        TextView tvVersion = (TextView) this.findViewById(R.id.text_version);
        tvLogin = (TextView) this.findViewById(R.id.text_login);
        ivLoading = (ImageView) this.findViewById(R.id.img_round);

        layout_bg.setOnClickListener(this);
        showPwdView.setOnClickListener(this);
        relLogin.setOnClickListener(this);
        tvVersion.setText(getString(R.string.version, getVersion()));
        editOperationCode.addTextChangedListener(textWatcherCode);
        editPwd.addTextChangedListener(textWatcherPsd);
        checkLoginBtn();

        // 监听软键盘的完成按钮
        editPwd.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editPwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (pwdLength >= 4 && operationCodeLength == 2) {
                        relLogin.performClick();
                        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        return true;
                    } else {
                        MToast.showToast(getString(R.string.login_erro), Toast.LENGTH_LONG);
                    }
                }
                return false;
            }

        });
    }

    private TextWatcher textWatcherCode = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            operationCodeLength = s.length();
            checkLoginBtn();
        }

    };

    private void startAnimation() {
        ivLoading.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, sunmi.sunmiui.R.anim.loading_anim);
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);
        ivLoading.setAnimation(animation);
        ivLoading.startAnimation(animation);
    }

    private void hideAnimation() {
        ivLoading.clearAnimation();
        ivLoading.setVisibility(View.GONE);
    }

    private TextWatcher textWatcherPsd = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            pwdLength = s.length();
            checkLoginBtn();
        }

    };

    private void checkLoginBtn() {
        if (pwdLength >= 4 && operationCodeLength == 2 && canLogin) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                relLogin.setBackgroundResource(R.drawable.login_click_ripple);
            }
            relLogin.setOnClickListener(this);
        } else {
            relLogin.setBackgroundResource(R.drawable.bg_gray_corner_login_btn);
            relLogin.setOnClickListener(null);
        }
    }

    private String getVersion() {
        return BuildConfig.VERSION_NAME;
    }

    @Override
    public void onBackPressed() {
        if (isSignOut) {
            exitActivity();
        } else {
            super.onBackPressed();
        }
    }

    // 记录第一次点击的时间
    private long clickTime = 0;

    private void exitActivity() {
        long time = System.currentTimeMillis() - clickTime;
        if (time > 2000) {
            Toast.makeText(this, getString(R.string.toa_exit_tips), Toast.LENGTH_SHORT).show();
            clickTime = System.currentTimeMillis();
        } else {
            sendCloseAppBroadcast();
        }
    }

    public static void startAction(Context context, boolean signOut) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(EXTRA_SIGN_OUT, signOut);
        context.startActivity(intent);
    }

}
